﻿using System;
using System.Collections.Generic;
using IBatisNet.DataAccess;
using IBatisNet.DataAccess.Configuration;
using IBatisNet.Common.Utilities;
using System.IO;

namespace curbside.IBatis
{
    public class ServiceConfig
    {
        /// <summary>
        /// 私有化构造函数
        /// </summary>
        private ServiceConfig() { }

        private static object _lock = new object();

        /// <summary>
        /// 定义字典存储各种数据库会话
        /// </summary>
        private static volatile Dictionary<string, IDaoManager> _daoManagerDictionary = new Dictionary<string, IDaoManager>();

        /// <summary>
        /// 是否初始化配置文件标志
        /// </summary>
        private static bool configInited = false;

        /// <summary>
        /// 设置监控委托函数
        /// 监控到文件更改时调用
        /// </summary>
        /// <param name="obj"></param>
        protected static void Configure(object obj)
        {
            _daoManagerDictionary.Clear();
            configInited = false;
        }

        /// <summary>
        /// 初始化配置文件（dao.config）
        /// </summary>
        protected static void InitManager()
        {
            ConfigureHandler handler = new ConfigureHandler(Configure);
            DomDaoManagerBuilder builder = new DomDaoManagerBuilder();
            string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"config\ibatis\dao.config");
            builder.ConfigureAndWatch(filePath, handler);
        }

        /// <summary>
        /// 取得DaoManager对象
        /// </summary>
        /// <param name="contextName">数据库上下文名称</param>
        /// <returns></returns>
        public static IDaoManager GetDaoManager(string contextName)
        {
            if (!_daoManagerDictionary.ContainsKey(contextName))
            {
                lock (_lock)
                {
                    if (!_daoManagerDictionary.ContainsKey(contextName))
                    {
                        if (!configInited)
                        {
                            InitManager();
                            configInited = true;
                        }

                        _daoManagerDictionary[contextName] = DaoManager.GetInstance(contextName);
                    }
                }
            }

            return _daoManagerDictionary[contextName];
        }
    }
}
